package com.ludomancy.gamelib.ui;

import java.awt.Cursor;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;

import com.ludomancy.gamelib.GameCanvas;
import com.ludomancy.gamelib.Utils;
import com.ludomancy.gamelib.Widget;


public class Button extends Widget
{
	private String buttonLabel = "";
	private static final int STATE_IDLE = 0;
	private static final int STATE_PRESSED = 1;
	private int state = STATE_IDLE;
	private ButtonListener listener;
	
	public interface ButtonListener
	{
		void onPress(Button widget);
	}
	
	public Button(Widget parent, Rectangle area, String label, ButtonListener listener)
	{
		super(parent, area);
		this.listener = listener;
		buttonLabel = label;
	}
	
	public void setListener(ButtonListener listener)
	{
		this.listener = listener;
	}
	
	public void paint(Graphics g)
    {
    	if(state == STATE_IDLE)
    	{
    		getTheme().fillButton(g, new Rectangle(0,0,getWidth(), getHeight()), false);
    	}
    	else
    	{
    		getTheme().fillButton(g, new Rectangle(0,0,getWidth(), getHeight()), true);
    	}
    	g.setColor(getTheme().getDefaultTextColor());
        g.setFont(getTheme().getDefaultFont());
        // get the text bounds
        Point p = Utils.stringSize(g.getFont(), buttonLabel);
        // center the label into the box
        int px = (getWidth() - p.x)/2;
        g.setColor(getTheme().getDefaultTextColor());
        //Utils.drawString(g, buttonLabel, px, py);
        Utils.drawStringVerticallyCentered(g, buttonLabel, px, getHeight()/2);
    }
	
	public void onMouseEnter()
	{
		if(GameCanvas.screen.cursorVisible)
		{
			Cursor hand = Cursor.getPredefinedCursor(Cursor.HAND_CURSOR);
			GameCanvas.screen.setCursor(hand);
		}
	}
	
	public void onMouseLeave()
	{
		if(GameCanvas.screen.cursorVisible)
		{
			Cursor hand = Cursor.getDefaultCursor();
			GameCanvas.screen.setCursor(hand);
		}
	}
	
    public void mouseDown(Point p)
    {
   		state = STATE_PRESSED;
   		mouseCapture();
    }
    
    public void mouseUp(Point p)
    {
    	boolean isIn = getClientRect().contains(p.x, p.y);
    	if(isIn && (state == STATE_PRESSED))
    	{
    		listener.onPress(this);
    	}
    	mouseRelease();
    	state = STATE_IDLE;
    }

	public String getLabel()
	{
		return buttonLabel;
	}

	public void setLabel(String string)
	{
		buttonLabel = string;
	}
}
